<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学期" prop="semId">
        <el-select v-model="queryParams.semId" filterable clearable placeholder="请选择学期">
          <el-option
            v-for="item in semsterList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            size="small">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班级" prop="classId">
        <el-select v-model="queryParams.classId" filterable clearable placeholder="请选择班级">
          <el-option
            v-for="item in clazzList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            size="small">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学生" prop="stuName">
        <el-input
          v-model="queryParams.stuName"
          placeholder="请输入学生"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        <el-form-item label="规则" prop="ruleId">
          <el-select v-model="queryParams.ruleId" filterable clearable placeholder="请选择规则" @input="changeRule">
            <el-option
              v-for="item in ruleList"
              :key="item.id"
              :label="item.title+ '('+ modeFormat(item) + item.score + ')'"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
      <el-form-item label="计分规则" prop="mode">
        <el-select v-model="queryParams.mode" placeholder="请选择计分规则" clearable size="small">
          <el-option
            v-for="dict in modeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="考核时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['quantify:student:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['quantify:student:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['quantify:student:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
          v-hasPermi="['quantify:student:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学期" align="center" prop="semName" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="学生" align="center" prop="stuName" />
      <el-table-column label="学号" align="center" prop="stuCode" />
      <el-table-column label="规则" align="center" prop="ruleName" />
      <el-table-column label="计分规则" align="center" prop="mode" :formatter="modeFormat" />
      <el-table-column label="分数" align="center" prop="score" />
      <el-table-column label="考核日期" align="center" prop="dates" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dates, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="节次" align="center" prop="sectionName" />
      <el-table-column label="详细说明" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['quantify:student:edit']"
          >修改</el-button>
          -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['quantify:student:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改量化考核对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学期" prop="semId">
          <el-select v-model="form.semId" filterable clearable placeholder="请选择学期">
            <el-option
              v-for="item in semsterList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="form.classId" filterable clearable placeholder="请选择班级" @input="changeClass">
            <el-option
              v-for="item in clazzList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生" prop="stuIds">
          <el-select v-model="form.stuIds" filterable multiple clearable placeholder="请选择学生">
            <el-option
              v-for="item in stuList"
              :key="item.id"
              :label="item.name + '('+ item.code + ')'"
              :value="item.userId"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规则" prop="ruleId">
          <el-select v-model="form.ruleId" filterable clearable placeholder="请选择规则" @input="changeRule">
            <el-option
              v-for="item in ruleList"
              :key="item.id"
              :label="item.title+ '('+ modeFormat(item) + item.score + ')'"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考核日期" prop="dates">
          <el-date-picker clearable size="small"
            v-model="form.dates"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择考核日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="节次" prop="sectionId" v-if="rule && rule.type == '1'">
          <el-select v-model="form.sectionId" filterable clearable placeholder="请选择规则" @input="changeRule">
            <el-option
              v-for="item in sectionList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入详细说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的量化数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStudent, getStudent, delStudent, addStudent, updateStudent, exportStudent, importTemplate } from "@/api/quantify/student";
import { selectSemster} from "@/api/base/semster";
import { selectSection} from "@/api/base/section";
import { selectStudent} from "@/api/base/student";
import { listClazz} from "@/api/base/clazz";
import { selectRule} from "@/api/quantify/rule";
import { getToken } from "@/utils/auth";

export default {
  name: "Student",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 量化考核表格数据
      studentList: [],
      // 学期数据
      semsterList: [],
      // 节次数据
      sectionList: [],
      // 规则数据
      ruleList: [],
      // 班级数据
      clazzList: [],
      // 学生数据
      stuList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 计分规则字典
      modeOptions: [],
      rule: null,
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/quantify/student/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn:"t.id",
        isAsc:"DESC",
        stuId: null,
        semId: null,
        classId: null,
        ruleId: null,
        mode: null,
        score: null,
        dates: null,
        sectionId: null,
      },
      dateRange: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        classId: [
          { required: true, message: "班级不能为空", trigger: "blur" }
        ],
        stuIds: [
          { required: true, message: "学生不能为空", trigger: "blur" }
        ],
        ruleId: [
          { required: true, message: "规则不能为空", trigger: "blur" }
        ],
        score: [
          { required: true, message: "分数不能为空", trigger: "blur" }
        ],
        dates: [
          { required: true, message: "考核日期不能为空", trigger: "blur" }
        ],
        semId: [
          { required: true, message: "学期不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("score_mode").then(response => {
      this.modeOptions = response.data;
    });
    selectSemster({'status':1}).then(response => {
      this.semsterList = response.rows;
    });
    selectSection({'status':1}).then(response => {
      this.sectionList = response.rows;
    });
    selectRule({'status':1}).then(response => {
      this.ruleList = response.rows;
    });
    listClazz({'status':1}).then(response => {
      this.clazzList = response.rows;
    });
  },
  methods: {
    /** 查询量化考核列表 */
    getList() {
      this.loading = true;
      listStudent(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.studentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 计分规则字典翻译
    modeFormat(row, column) {
      return this.selectDictLabel(this.modeOptions, row.mode);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stuId: null,
        stuIds: [],
        classId: null,
        ruleId: null,
        mode: "0",
        score: null,
        dates: null,
        sectionId: null,
        remark: null,
        semId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    changeClass(){      
      selectStudent({'status':1, classId:this.form.classId}).then(response => {
        this.stuList = response.rows;
      });
    },
    changeRule() {
      for(var i=0;i<this.ruleList.length;i++){
        if(this.ruleList[i].id == this.form.ruleId){
          this.rule = this.ruleList[i];
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();      
      for(var i=0;i<this.semsterList.length;i++){
        if(this.semsterList[i]['isCurrent'] == 'Y') this.form.semId = this.semsterList[i].id;
      }
      this.open = true;
      this.title = "添加量化考核";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStudent(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改量化考核";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStudent(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStudent(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除量化考核编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delStudent(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有量化考核数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportStudent(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "学生量化考核导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
